package com.dfiles.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.dfiles.R;

public class DSpinner extends Spinner {
	public static final int THEME1 = 100;
	public static final int THEME2 = 101;
	private List<Object> list;
	private Context mContext;
	private int mode = Spinner.MODE_DROPDOWN;
	private boolean ascOrDesc = true;/* 默认true表示正向 */
	private boolean ascAndDescUseful = false;/* 正反向是否起作用 */
	private int position = -1;

	public DSpinner(Context context, AttributeSet attrs, int defStyle) {
		this(context, attrs, defStyle, Spinner.MODE_DROPDOWN);
		// TODO Auto-generated constructor stub
	}

	public DSpinner(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public DSpinner(Context context, int mode) {
		this(context, null, 0, mode);
		// TODO Auto-generated constructor stub
	}

	public DSpinner(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	public DSpinner(Context context, AttributeSet attrs, int defStyle, int mode) {
		super(context, attrs, defStyle, mode);
		mContext = context;
		this.mode = mode;
		// initData();
	}

	private void initData(int theme) {
		if (list == null) {
			list = new ArrayList<Object>();
		}
		int topResId = (theme == THEME1) ? R.layout.common_spinner_top_style : R.layout.common_spinner_top_style1;
		ArrayAdapter adapterOrder = new ArrayAdapter(mContext, topResId, list);
		adapterOrder.setDropDownViewResource(R.layout.common_dropdown_item);
		setAdapter(adapterOrder);
		setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int p, long id) {
				if (onItemSelected != null) {
					if (ascAndDescUseful) {

						ascOrDesc = true;
					} else {
						ascOrDesc = !ascOrDesc;
					}
					position = p;
					onItemSelected.onItemSelected(view, position, id, ascOrDesc);
				}
			}

			public void onNothingSelected(AdapterView<?> paramAnonymousAdapterView) {
			}
		});
	}

	public List<Object> getList() {
		return list;
	}

	public void setList(List<Object> list, int theme) {
		this.list = list;
		initData(theme);
	}

	public interface OnItemSelectedListener {
		void onItemSelected(View view, int position, long id, boolean ascOrDesc);
	}

	private OnItemSelectedListener onItemSelected;

	public void setOnItemSelectedListener(OnItemSelectedListener onItemSelected) {
		this.onItemSelected = onItemSelected;
	}

}
